<?php
session_start();
function checkConfigFile(){
	global $cfg;
	$configFile = $cfg->_iniFilename;
	//check if the configuration file exists
	if(!file_exists($configFile)){
		//the configuration file doesn't exist at the expected location
		echo "The configuration file does not exist at: " . $configFile . "<br />";
		
		//check to see if the sample configuration file exists
		if(file_exists("../configuration/config.sample.ini")){
			echo "The sample configuration file exists. Attempting to copy over sample configuration file... <br />";
			//move the sample configuration file to where we expect the configuration file to be
			if(copy("../configuration/config.sample.ini", $configFile)){
				//if we were able to copy the file, let the user know then redirect them
				echo "We were able to copy over the sample configuration file. If the page does not reload in five seconds, please do it manually. <br />";
				echo "<span style='color:#336600;weight:bold;border:1px solid #336600;background-color:#66CC66;display:block;padding:5 20;'>SUCCESS! Redirecting...</span>";
				//reload the page in a few seconds
				header( "refresh:5;" );
				//clear anything else that was about to come out.
				exit;
			}
			else{
				echo "We were unable to automatically move over the sample configuration file." .
						"You can do this yourself by renaming the config.sample.ini file in the configuration to config.ini <br />";
				exit;
			}
		}
		else{
			echo "Critical error: The sample configuration file does not exist. <br />";
			exit;
		}
	}

}
function getConfigVars($displayAppFullPath = false) {
    //make the variables global so they can be used outside the function
    global $cfg, $config_newzenabled, $config_newzuname, $config_newzpw, 
			$config_nzbmatrixenabled, $config_nzbmatrixuname, $config_nzbmatrixapikey, 
			$config_sabnzbd_enable,$config_sabnzbd_apikey,$config_sabnzbd_url,$config_sabnzbd_uname,$config_sabnzbd_pass,
			$config_NZBDropPath, $config_deleteupondl, $config_sabnzbdnaming_enable, $config_NZBgetAppPath, $config_NZBgetConfigPath, 
			$config_enablenzbget, $config_enablehistorydisp, $config_enablepostprocdisp, $config_nzbgetDLdetails, 
			$config_nzbgetautorefresh, 
			$config_inet_password, $config_inet_protection, 
			$config_memory_limit, $config_inet_hash, $config_saved_searches, 
			$config_filemandefaultpath, $config_remoteplay, $remoteplayenabled, $config_stripslashes,
			$config_theme_default, $config_theme_mobile, $config_theme_local,
			$config_xbmc_enabled, $config_xbmc_location, $config_xbmc_port, $config_xbmc_username, $config_xbmc_password;
    
	//first check to see if the configuration file is valid
	checkConfigFile();
	
    //get the saved variables
    //Newzbin
	$config_newzenabled = $cfg->get("Newzbin","enabled"); 
	$config_newzuname = $cfg->get("Newzbin","username"); 
    $config_newzpw = $cfg->get("Newzbin","password");
	//NZBMatrix
	$config_nzbmatrixenabled = $cfg->get("NZBMatrix","enabled"); 
	$config_nzbmatrixuname = $cfg->get("NZBMatrix","username"); 
    $config_nzbmatrixapikey = $cfg->get("NZBMatrix","apikey");
	//SABnzbd
	$config_sabnzbd_enable = $cfg->get("SABnzbd","enable"); 
	$config_sabnzbd_apikey = $cfg->get("SABnzbd","apikey"); 
	$config_sabnzbd_url = $cfg->get("SABnzbd","url"); 
	$config_sabnzbd_uname = $cfg->get("SABnzbd","uname"); 
	$config_sabnzbd_pass = $cfg->get("SABnzbd","pass"); 
    //General
	$config_NZBDropPath = $cfg->get("Newzbin","NZBDropPath");
    $config_deleteupondl = $cfg->get("Newzbin","deleteupondl");
	$config_sabnzbdnaming_enable = $cfg->get("General","sabnzbdnaming_enable");
    //NZBGet
	$config_NZBgetAppPath = $cfg->get("NZBget","NZBgetAppPath");
    $config_NZBgetConfigPath = $cfg->get("NZBget","NZBgetConfigPath");
    $config_enablenzbget = $cfg->get("NZBget","enablenzbget");
    $config_enablehistorydisp = $cfg->get("NZBget","enablehistorydisp");
    $config_enablepostprocdisp = $cfg->get("NZBget","enablepostprocdisp");
    $config_nzbgetDLdetails = $cfg->get("NZBget","nzbgetDLdetails");
    $config_nzbgetautorefresh = $cfg->get("NZBget","nzbgetautorefresh");
    //Internet
	$config_inet_password = $cfg->get("Internet Security","inet_password");
    $config_inet_protection = $cfg->get("Internet Security","inet_protection");
    $config_memory_limit = $cfg->get("System","memory_limit");
    $config_inet_hash = $cfg->get("Internet Security","inet_hash");
    $config_saved_searches = $cfg->get("Newzbin","savedsearches");
    $config_filemandefaultpath = $cfg->get("Fileman","defaultpath");
    $config_remoteplay = $cfg->get("Fileman","remoteplay");
    if($config_remoteplay == "enable"){ $remoteplayenabled = true; }else{ $remoteplayenabled = false; }
	$config_stripslashes = $cfg->get("Fileman","stripslashes");
    $config_theme_default = $cfg->get("Themes","default"); 
    //if the default theme stored in the configuration doesn't exists, let's temporarily set it to the default (without changing the configuration)
    if(!file_exists("./style/$config_theme_default")){ $config_theme_default = 'default.css'; }
    $config_theme_mobile = $cfg->get("Themes","mobile"); 
    ////if the mobile theme stored in the configuration doesn't exists, let's temporarily set it to the default (without changing the configuration)
    if(!file_exists("./style/$config_theme_mobile")){ $config_theme_mobile = 'default.css'; }
    $config_theme_local = $cfg->get("Themes","local"); 
    ////if the local theme stored in the configuration doesn't exists, let's temporarily set it to the default (without changing the configuration)
    if(!file_exists("./style/$config_theme_local")){ $config_theme_local = 'default.css'; }

    if($displayAppFullPath){
        $config_NZBgetAppPath = $config_NZBgetAppPath."/nzbget";
        $config_NZBgetConfigPath = $config_NZBgetConfigPath."/nzbget.conf";
    }
	
	//XBMC
	$config_xbmc_enabled = $cfg->get("XBMC","enabled"); 
	$config_xbmc_location = $cfg->get("XBMC","location"); 
	$config_xbmc_port = $cfg->get("XBMC","port"); 
	$config_xbmc_username = $cfg->get("XBMC","username"); 
	$config_xbmc_password = $cfg->get("XBMC","password"); 
    
    return true;
}
function standardHead($pageName = "NewzBook") {
    global $mobile, $config_theme_mobile, $config_theme_local, $config_theme_default, $cfg;
    ?>
    <!-- START: Standardized NewzBook Header Content -->
    <TITLE><?php echo $pageName." - ".$cfg->get("Application","name")." v".$cfg->get("Application","version"); ?></TITLE>
    <link rel="apple-touch-icon" href="images/custom_icon.png"/>
    <!--<meta name="viewport" content = "user-scalable=no">
	<meta name="viewport" content="width=device-width">-->
    <meta name="viewport" content = "initial-scale=1.0">
    <?php
    //if we have a mobile user (using the iPhone theme), let's try to auto-scroll them to the main content
    if($mobile && $config_theme_mobile == "iPhone.css"){ ?>
        <SCRIPT TYPE="text/javascript">
          //window.onload = function(){ window.scrollTo(0,1) }
        </SCRIPT>
    <?php }
    if($mobile){ echo "<link rel='stylesheet' type='text/css' href='style/$config_theme_mobile' />"; }
    elseif($_SERVER['REMOTE_ADDR'] == "127.0.0.1"){ echo "<link rel='stylesheet' type='text/css' href='style/$config_theme_local' />"; }
    else { echo "<link rel='stylesheet' type='text/css' href='style/$config_theme_default' />"; }
    ?>
    
    <SCRIPT TYPE="text/javascript">
    <!--
    function popup(mylink, windowname) {
        if (!window.focus)return true;
        var href;
        if (typeof(mylink) == 'string')
           href=mylink;
        else
           href=mylink.href;
        newwindow=window.open(href, windowname, 'width=750,height=480,scrollbars=no');
        if (window.focus){newwindow.focus()}
        return false;
    }
    function popupSmall(mylink, windowname) {
        if (! window.focus)return true;
        var href;
        if (typeof(mylink) == 'string')
           href=mylink;
        else
           href=mylink.href;
        newwindow=window.open(href, windowname, 'width=300,height=200,scrollbars=no');
        if (window.focus){newwindow.focus()}
        return false;
    }
    function popupController(mylink, windowname){
        if (!window.focus)return true;
        var href;
        if (typeof(mylink) == 'string')
           href=mylink;
        else
           href=mylink.href;
        newwindow=window.open(href, windowname, 'width=200,height=50,scrollbars=no,location=no,status=no,titlebar=no,toolbar=no,menubar=no');
        if (window.focus){newwindow.focus()}
        
        return false;
    }
    //-->
    </SCRIPT>
    <script language="javascript" type="text/javascript">
    function loadSubmit() {

    ProgressImage = document.getElementById('progress_image');
    document.getElementById("progress").style.visibility = "visible";
    document.getElementById("progress").style.display = "block";
    setTimeout("ProgressImage.src = ProgressImage.src",100);
    window.location.hash="loading";
    return true;

    } 
    </script>
    <!-- END: Standardized NewzBook Header Content -->
    <?php
}
function internetSecurity() {
    //make the configuration available to the function (via global)
    global $cfg;
    
    //if the action is set, check if it's logout
    if(isset($_GET['action'])){
        if($_GET['action']=="logout"){
            //if the action is logout, let's destroy the session
            $_SESSION['loggedin'] = 0;
            session_destroy();
            echo "You have been logged out.";
            header("Location: index.php");
        }
    }
    //if the session is set, let's check it
    if(isset($_SESSION['loggedin'])){
        //if the user is already logged in, we don't need to do anything
        if($_SESSION['loggedin'] == 1){
            return 1;
        }
    }
    //if the user tried to use a hash (and it's valid), we don't need to continue
    if(isset($_GET['inet_hash'])){
        $inet_hash = $_GET['inet_hash'];
        //Lets make sure the user provided hash matches our configuration (and check to make sure it doesn't match because it's blank or null)
        if($inet_hash != "" && $inet_hash != null && $inet_hash == $cfg->get("Internet Security","inet_hash")){
            return 1;
        }
    }
    
    if($cfg->get("Internet Security","inet_protection") == "enable"){
        $localIP[0] = "192.168"; // For viewing pages on remote server on local network
        $localIP[1] = "127.0.0"; // For viewing pages while logged on to server directly
        $localIP[2] = substr($_SERVER['SERVER_ADDR'], 0, 7);

        $register_globals = (bool) ini_get('register_gobals');
        if ($register_globals) $ip = getenv(REMOTE_ADDR);
        else $ip = $_SERVER['REMOTE_ADDR'];

        $check = substr($ip, 0, 7); 
        if ($check == $localIP[0] || $check == $localIP[1] || $check == $localIP[2]) { 
            //no need to check for the password
            return 1;
        }
        else {
            if(inetPasswordCheck() == FALSE){
                echo "The internet security option has been enabled, which requires you to log in when accessing the application from outside your local network.<br/>";
                die(inetPasswordForm());
            }
        }
    }
}
function inetPasswordForm() {
    $PWform = "<form action='' method='POST'>
               Password: <input type='password' name='inetpassword'/>
               <input type='submit' value='Login'/>
               </form>";
    echo $PWform;
    return;
}
function inetPasswordCheck() {
    //include the global variables required for this function
    global $cfg;
    
    //if the password is set, let's sha1 hash it and check it against the stored password
    if(isset($_POST['inetpassword'])){
        if($cfg->get("Internet Security","inet_password") == sha1($_POST['inetpassword'])) {
            //The passwords match
            $_SESSION['loggedin'] = TRUE;
            return TRUE;
        }
        else {
            //The passwords do NOT match
            return FALSE;
        } 
    }
    //inetpassword wasn't set
    return FALSE;
}
function headerContent() {
  global $cfg, $mobile, $config_sabnzbd_enable, $config_enablenzbget, $config_xbmc_enabled;
  ?>
  <!-- START: Standardized NewzBook Header Content -->
  <h1 class='headerlogo'><?php echo $cfg->get("Application","name");?></h1>
  <!-- START: Navigation -->
  <div class="nav_first"></div>
  <ul class='navigation'>
    <li><a href='index.php'>Bookmarks</a></li>
    <li><a href='nzbsearch.php'>Search</a></li>
	<?php if($config_enablenzbget=="enable"){ ?>
		<li><a href='nzbget.php'>NZBget</a></li>
	<?php } ?>
	<?php if($config_sabnzbd_enable=="enable"){ ?>
		<li><a href='sabnzbd.php'>SABnzbd</a></li>
	<?php } 
	if($config_xbmc_enabled=="enable"){
	?>
		<li><a href='filemanXBMC.php'>XBMC Remote</a></li>
	<?php } ?>
	<li><a href='fileman.php'>File Manager</a></li>
    <?php if(!$mobile && $_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ ?>
        <li><a onclick="return popup(this, 'notes')" href="mediaplayer.php">Media Player</a></li>
    <?php } ?>
    <li><a href='configuration.php'>Configuration</a></li>
    <?php if(isset($_SESSION['loggedin'])){if($_SESSION['loggedin']==1){ ?>
        <li><a href='?action=logout'>Logout</a></li>
    <?php }} ?>
  </ul>
  <div class="nav_last"></div>
  <!-- END: Navigation -->
  <!-- END: Standardized NewzBook Header Content -->
  <?php
}
function sendCommand($command) {
  switch($command) {
    case 'nav_left':	exec ('echo $((0xAA)) > /tmp/irkey');	break;
    case 'nav_right':	exec ('echo $((0xAB)) > /tmp/irkey');	break;
    case 'nav_up':		exec ('echo $((0xA8)) > /tmp/irkey');	break;
    case 'nav_down':	exec ('echo $((0xA9)) > /tmp/irkey');	break;
    case 'nav_ok':		exec ('echo $((0x0D)) > /tmp/irkey');	break;

    case 'play':		exec ('echo $((0xE9)) > /tmp/irkey');	break;
    case 'pause':		exec ('echo $((0xEA)) > /tmp/irkey');	break;
    case 'slow':		exec ('echo $((0xD9)) > /tmp/irkey');	break;
    case 'stop':		exec ('echo $((0x1B)) > /tmp/irkey');	break;
    case 'rew':			exec ('echo $((0xD5)) > /tmp/irkey');	break;
    case 'fwd':			exec ('echo $((0xD6)) > /tmp/irkey');	break;
    case 'prev':		exec ('echo $((0xDB)) > /tmp/irkey');	break;
    case 'next':		exec ('echo $((0xDC)) > /tmp/irkey');	break;

    case 'back':		exec ('echo $((0x8D)) > /tmp/irkey');	break;
    case 'home':		exec ('echo $((0xD0)) > /tmp/irkey');	break;
    case 'info':		exec ('echo $((0x95)) > /tmp/irkey');	break;
    case 'zoom':		exec ('echo $((0xDA)) > /tmp/irkey');	break;

    case 'volume_up':	exec ('echo $((0x9E)) > /tmp/irkey');	break;
    case 'volume_down':	exec ('echo $((0x9F)) > /tmp/irkey');	break;
    case 'volume_mute':	exec ('echo $((0xE1)) > /tmp/irkey');	break;

    case 'page_up':		exec ('echo $((0x9E)) > /tmp/irkey');	break;
    case 'page_down':	exec ('echo $((0x9F)) > /tmp/irkey');	break;

    case 'num_0':		exec ('echo $((0xF1)) > /tmp/irkey');	break;
    case 'num_1':		exec ('echo $((0xF2)) > /tmp/irkey');	break;
    case 'num_2':		exec ('echo $((0xF3)) > /tmp/irkey');	break;
    case 'num_3':		exec ('echo $((0xF4)) > /tmp/irkey');	break;
    case 'num_4':		exec ('echo $((0xF5)) > /tmp/irkey');	break;
    case 'num_5':		exec ('echo $((0xF6)) > /tmp/irkey');	break;
    case 'num_6':		exec ('echo $((0xF7)) > /tmp/irkey');	break;
    case 'num_7':		exec ('echo $((0xF8)) > /tmp/irkey');	break;
    case 'num_8':		exec ('echo $((0xF9)) > /tmp/irkey');	break;
    case 'num_9':		exec ('echo $((0xFA)) > /tmp/irkey');	break;

    case 'menu':		exec ('echo $((0x09)) > /tmp/irkey');	break;
    case 'subtitle':	exec ('echo $((0xEB)) > /tmp/irkey');	break;
    case 'audio':		exec ('echo $((0xD8)) > /tmp/irkey');	break;
    case 'setup':		exec ('echo $((0x8C)) > /tmp/irkey');	break;
    case 'source':		exec ('echo $((0xDD)) > /tmp/irkey');	break;
    case 'power':		exec ('echo $((0xD2)) > /tmp/irkey');	break;
    case 'red':			exec ('echo $((0xDE)) > /tmp/irkey');	break;
    case 'green':		exec ('echo $((0xDF)) > /tmp/irkey');	break;
    case 'yellow':		exec ('echo $((0xE0)) > /tmp/irkey');	break;
    case 'blue':		exec ('echo $((0xE2)) > /tmp/irkey');	break;
    case 'del':			exec ('echo $((0x08)) > /tmp/irkey');	break;
    case 'caps':		exec ('echo $((0xFC)) > /tmp/irkey');	break;
    case 'timeseek':	exec ('echo $((0x91)) > /tmp/irkey');	break;
    case 'repeat':		exec ('echo $((0x90)) > /tmp/irkey');	break;
    case 'angle':		exec ('echo $((0xEC)) > /tmp/irkey');	break;
    case 'tv_mode':		exec ('echo $((0x8F)) > /tmp/irkey');	break;
    case 'eject':		exec ('echo $((0xEF)) > /tmp/irkey');	break;
    case 'title':		exec ('echo $((0x94)) > /tmp/irkey');	break;
  }
}
function displayController($fullpath = null, $urlFirstPath = null, $urlLastPath = null){
    //we are no longer using different links for the controller in different places
    $onClick = "onClick=\"return popupController(this,'remoteController')\"";
	if($urlFirstPath == null){
		$urlFirstPath = "playlistmanager.php?action=displayRemoteController";
	}
    
    //if the user didn't specifically set the fullpath, let's set our own (this is for backwards compatibility and might get pulled out in the future)
    if($fullpath == null){
        //$urlFirstPath = "playlistmanager.php?";
        $onClick = null;
    }/*
    else{
        $urlFirstPath = "?path=".urlencode($fullpath)."&";
    }*/
    
    //output the different buttons
    //play
    echo "<a href='".$urlFirstPath."&command=play".$urlLastPath."' $onClick ><img src='images/control_play.png'/></a>";
    //pause
    echo "<a href='".$urlFirstPath."&command=pause".$urlLastPath."' $onClick ><img src='images/control_pause.png'/></a>";
    //stop
    echo "<a href='".$urlFirstPath."&command=stop".$urlLastPath."' $onClick ><img src='images/control_stop.png'/></a>";
    //rew
    echo "<a href='".$urlFirstPath."&command=rew".$urlLastPath."' $onClick ><img src='images/control_rewind.png'/></a>";
    //fwd
    echo "<a href='".$urlFirstPath."&command=fwd".$urlLastPath."' $onClick ><img src='images/control_fastforward.png'/></a>";
    //next
    echo "<a href='".$urlFirstPath."&command=next".$urlLastPath."' $onClick ><img src='images/control_start.png'/></a>";
    //prev
    echo "<a href='".$urlFirstPath."&command=prev".$urlLastPath."' $onClick ><img src='images/control_end.png'/></a>";
}
function checkNewzBookVersion(){
    global $config_versionCheck, $config_repositoryLocation, $cfg;
    //set the variables... in the future, these will be stored in the configuration file
    $config_versionCheck = "enable";
    $config_repositoryLocation = "http://newzbook.googlecode.com/svn/downloads/RepositoryInfo.xml";
    $currentVersion = $cfg->get("Application","version");
    
    //if the user has enabled version checking, let's check for the new version
    if($config_versionCheck == "enable"){
        //get the contents of the repository file
        $repositoryContents = file_get_contents($config_repositoryLocation);
        //if we couldn't get the contents, let the user know
        if($repositoryContents == false){
            return "Cannot check version. Could not contact the repository";
        }else{
        //otherwise let's split out the contents of the file and let the user know where they can get the new version
            $pattern = "/.*\<Version\>([^\<]+)\<\/version\>.*/msi";
            preg_match($pattern, $repositoryContents, $matches);
            //print_r($matches);
            $latestVersion = $matches[1];
            $return = "<div class='small' style='float:right'>";
            if($latestVersion == $currentVersion){
                $return .= "<font color='green'>You are running the latest version ($latestVersion).</font>";
            }else{
                $return .= "<font color='red'>You should update to $latestVersion.</font>";
            }
            $return .= "</div>";
            return $return;
            
        }
    }
    //
}
/******************************************************************\
 *  PLAY FILE                                                     *
 * ----------------------------------------                       *
 * This function plays the requested file remotely on the Popcorn *
 * Hour (PCH). 
 * 
 * Note: This function plays a SINGLE file.
 *
 * $file = the full path to the file (typically //share/file.type)*
 * $options = 
\******************************************************************/
function playFile($file, $options){
    $file = htmlspecialchars($file, ENT_QUOTES);
		
		if ($fp = fopen('/tmp/runmono.html', 'w')) {
			fwrite($fp, "<body bgcolor=black link=black onloadset='go'>");
			fwrite($fp, "<a onfocusload name='go' href='file://{$file}' {$options}></a>");
			fwrite($fp, "<a href='http://127.0.0.1:8883/start.cgi?list' tvid='home'></a>");
			fwrite($fp, "<a href='http://127.0.0.1:8883/start.cgi?list' tvid='source'></a>");
			fwrite($fp, "<br><font size='6' color='#ffffff'><b>Press Return on your remote to go back to your previous location</b></font>");
			fclose($fp);
		}

		exec("echo 212 > /tmp/irkey");
		exec("sleep 2");
		
		exec("killall amp_test");
		exec("killall mono");
		exec("killall pod");
		exec("echo /tmp/runmono.html > /tmp/gaya_bc");
}
/*******************************************************************\
 *  PLAY FILES                                                     *
 * ----------------------------------------                        *
 * This function plays the requested files remotely on the Popcorn *
 * Hour (PCH). This function will generate a PCH compatibile       *
 * playlist and send it to the PCH to be played.                   *
 *                                                                 *
 * Note: This function plays a multiple files.                     *
 *                                                                 *
 * $files = array of a list of file (with the fullpath for each)   *
\*******************************************************************/
function playFiles($files) {
		if ($fp = fopen('/tmp/runmono.jsp', 'w')) {
			foreach($files as $file){
				if (substr($file, 0, 1) == '/') {
					$file = 'file://' . $file;
				}
				
				fwrite($fp, $file . "|0|0|" . $file . "|\n");
			}		

			fclose($fp);
		}
		
		$file = '/tmp/runmono.jsp';
		$options = "pod='2,,'";
		
		if ($fp = fopen('/tmp/runmono.html', 'w')) {
			fwrite($fp, "<body bgcolor=black link=black onloadset='go'>");
			fwrite($fp, "<a onfocusload name='go' href='file://{$file}' {$options}></a>");
			fwrite($fp, "<a href='http://127.0.0.1:8883/start.cgi?list' tvid='home'></a>");
			fwrite($fp, "<a href='http://127.0.0.1:8883/start.cgi?list' tvid='source'></a>");
			fwrite($fp, "<br><font size='6' color='#ffffff'><b>Press Return on your remote to go back to your previous location</b></font>");
			fclose($fp);
		}

		exec("echo 212 > /tmp/irkey");
		exec("sleep 2");
			
		exec("killall amp_test");
		exec("killall mono");
		exec("killall pod");
		exec("echo /tmp/runmono.html > /tmp/gaya_bc");

}
function duration($secs){
	$vals = array('w' => (int) ($secs / 86400 / 7), 
                      'd' => $secs / 86400 % 7, 
                      'h' => $secs / 3600 % 24, 
                      'm' => $secs / 60 % 60, 
                      's' => $secs % 60); 

	$ret = array(); 

	$added = false; 
	foreach ($vals as $k => $v) { 
		if ($v > 0 || $added) { 
			$added = true; 
			$ret[] = $v . $k; 
		} 
	} 

	return join(' ', $ret); 
}
?>